<template>
  <div class="login-body">
    <div class="login-panel">

      <body  id="building">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120" class="demo-ruleForm" status-icon>
          <el-form-item style="color:white;" label="用户名" prop="accountName">
            <el-input v-model="ruleForm.employeeName" style="width: 200px;" placeholder="用户名" />
          </el-form-item>
          <el-form-item style="color:white;" label="密码" prop="accountPass">
            <el-input v-model="ruleForm.password" type="password" show-password placeholder="密码"
              style="width: 200px;" />
          </el-form-item>
          <el-form-item style="color:white;" label="验证码" prop="validateCode">
            <el-input v-model="ruleForm.validateCode" style="width: 200px;" placeholder="验证码" />
            <el-tag type="danger" style="font-size: 25px;height: 30px;" @click="setCode()">{{ ruleForm.vCode }}</el-tag>
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="ruleForm.remember" label="记住密码"></el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="submitForm(ruleFormRef)">
              登录
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>

            <el-button plain @click="dialogFormVisible = true">
              QQ邮箱登录
            </el-button>
          </el-form-item>
        </el-form>
      </body>
    </div>
  </div>

  <el-dialog v-model="dialogFormVisible" title="QQ邮箱登录" width="500">
    <el-form :model="form" ref="ruleFormRef" :rules="rules">
      <el-form-item label="请输入邮箱号" :label-width="formLabelWidth" prop="email_r">
        <el-input v-model="form.email_r" autocomplete="off" style="width: 200px;float: left;" />
        <el-button type="success" @click="Huoyan(ruleFormRef)" style="width: 120px;float: left;">
          发送验证码
        </el-button>
      </el-form-item>


      <el-form-item label="请输入验证码" :label-width="formLabelWidth">
        <el-input v-model="form.code" autocomplete="off" />
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="Login1(ruleFormRef)">
          邮箱登录
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';
import Cookie from 'cookies-ts'
import { useCounterStore } from '@/stores/counter';
const useStore = useCounterStore();
const apiurls = import.meta.env.VITE_APP_API_URL_RBACCommon;

const cookie = new Cookie()

const router = useRouter();
const route = useRoute();






//表单校验

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  employeeName: '',
  password: '',
  remember: false,
  validateCode: '',
  vCode: "2345"
})
const form = reactive({
  email_r: '',
  code: '',
})


const Huoyan = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate((valid, fields) => {
    if (valid) {




      axios.post('http://localhost:5214/api/UserRead/Code?email_r=' + form.email_r).then(function (response) {
        if (response.data == '发送成功') {
          ElMessage.success('发送成功')
          axios.post('http://localhost:5214/api/UserRead/UserEmailCreate', {
            email: form.email_r,
            code: form.code
          }).then(function (res) {
            if (res.data.code > 0) {
              ElMessage.success('新增成功')
            }
            else {
              ElMessage.error('新增失败')
            }

          })
        }
        else {
          ElMessage.error('发送失败')
        }

      })



      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })

}



const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

const Login1 = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.post('http://localhost:5214/api/UserRead/UserEmailLogin', {
        email: form.email_r,
        code: form.code
      }).then((response) => {
        if (response.data.result.code == 1) {
          ElMessage.success(response.data.result.msg)
          dialogFormVisible.value = false;

          //验证身份，并记录o
          localStorage.setItem("islogin", "true")

          //JWT
          window.localStorage.setItem("token", response.data.token);
          // 数据提交后端要加入新的Token值
          axios.defaults.headers.common["Authorization"] =
            "Bearer " + response.data.token;

          // router.push('/main')
          window.open('/main', '_self');
        }
        else {
          ElMessage.error(response.data.result.msg)
        }
      }

      )


    } else {
      console.log('error submit!', fields)
    }
  })


}


// const Login3 = () => {
//   axios.post('http://localhost:5214/api/UserRead/UserEmailLogin', {
//     email: form.email_r,
//     code: form.code
//   }).then((response) => {

//     if (response.data.result.code == 1) {
//       ElMessage.success(response.data.result.msg)
//       dialogFormVisible.value = false;

//       //验证身份，并记录o
//       localStorage.setItem("islogin", "true")

//       //JWT
//       window.localStorage.setItem("token", response.data.token);
//       // 数据提交后端要加入新的Token值
//       axios.defaults.headers.common["Authorization"] =
//         "Bearer " + response.data.token;
//       router.push('/main')
//     }
//     else {
//       ElMessage.error(response.data.result.msg)
//     }
//   }

//   )

// }


const rules = reactive<FormRules>({

  employeeName: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  password: [
    // {
    //   required: true,
    //   message: '请输入密码',
    //   trigger: 'change',
    // },
    { required: true, message: '密码不能为空', trigger: 'blur' },
  ],
  validateCode: [
    { required: true, message: '验证码不能为空', trigger: 'blur' },
    // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  email_r: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { message: '邮箱格式不正确', trigger: 'blur', pattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/ },
  ],
  code: [
    { required: true, message: '验证码不能为空', trigger: 'blur' },
  ],
})


//登录
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (ruleForm.validateCode.toLowerCase() != ruleForm.vCode.toLocaleLowerCase()) {
        ElMessage.error('验证码错误')
        return
      }
      Login()


      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}



const Login = () => {
  axios.post(apiurls + '/api/UserRead/UserLoginsQuery', ruleForm).then(res => {
    console.log(res.data.result)

    if (res.data.result.code == 0) {
      ElMessage.success(res.data.result.msg)
      //JWT
      window.localStorage.setItem("token", res.data.token);
      // 数据提交后端要加入新的Token值
      axios.defaults.headers.common["Authorization"] =
        "Bearer " + res.data.token;
      if (ruleForm.remember) {
        // localStorage.setItem('employeeName',ruleForm.employeeName)
        // localStorage.setItem('employeeName',ruleForm.employeeName)
        cookie.set('employeeName', ruleForm.employeeName)
        cookie.set('password', ruleForm.password)
      }
      else {
        // localStorage.removeItem('employeeName')
        // localStorage.removeItem('password')
        cookie.remove('employeeName')
        cookie.remove('password')
      }
      //验证身份，并记录
      localStorage.setItem("islogin", "true")
      useStore.isLogin = true;


      router.push('/main')
    } else {
      ElMessage.error(res.data.msg)
    }
  }).catch(err => {

  })
}

const loadData = () => {
  // if(localStorage.getItem('employeeName')!=null){
  //   ruleForm.employeeName=localStorage.getItem('employeeName') as string
  //   ruleForm.password=localStorage.getItem('password') as string
  //   ruleForm.remember=true
  // }
  if (cookie.get('employeeName') != null) {
    ruleForm.employeeName = cookie.get('employeeName') as string
    ruleForm.password = cookie.get('password') as string
    ruleForm.remember = true
  }
}
//验证码
const setCode = () => {
  let vcode = ""
  // for(let i=0;i<4;i++){
  //   let rand =Math.floor(Math.random()*10) ;
  //   codes+=rand
  // }
  // ruleForm.vCode=codes
  let codes = "0123456789zxcvbnmasdfghjklqwertyuiopZXCVBNMASSDFGHJKLQWERTYUIO"
  for (let i = 0; i < 4; i++) {
    let rand = Math.floor(Math.random() * codes.length);
    vcode += codes[rand]
  }
  ruleForm.vCode = vcode
}


const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}



onMounted(() => {
  loadData()
  setCode()
});




</script>

<style>
#building {
  background: url("../views/Img/国徽.png");
  width: 100%;
  height: 100%;
  position: fixed;
  background-size: 100% 100%;
}
</style>




<style scoped>
@media (min-width: 200px) {
  body {
    display: grid;
    place-items: center;
  }

  button:disabled {
    /* background-color: rgb(128, 128, 128); */
    background-color: white;
  }
}
</style>
